import blueTool from '../../utils/bluetooth'
import { crc8, formatEcgData, formatOxiData, formatTmpData, getEcgWaveChart, parseEcgFileData, parseResponse, readFileData, startReadPkg, stopReadPkg } from '../../utils/checkme'
import { dataConversion, hexStr2Num } from '../../utils/number'
import api from '../../../api/index'

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}

// package-checkme/pages/index/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    devices: [],
    connected: false,
    result: null,
    label: '',
    deviceId: null,
    ecgFiles: [],
    showWaveEchart: true,
    bindDeviceId: null,
    devicelist: [],
    actions: [],
    bindDevice: [],
    saveDevice: {},
    showDialog: false,
    bindDeviceTextInfo: '',
    loading: false,
    bleAvaible: true,
    beforeClose: null,
    available: false
  },

  ecgData: [],
  tmpData: [],
  oxiData: [],
  packageNum: 0,
  fileName: [],
  state: 0, // 0 start read 1 read content 2 end read
  bytesArray: [],
  fileData: [],
  timeValue: null,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { bleStatus } = options
		this.setData({
			available:bleStatus
		})
    this.get()
		this.doBluetoothAdapterStateChange()
    this.init()
  },
  doBluetoothAdapterStateChange() {
		wx.onBluetoothAdapterStateChange((res) => {
			console.log('蓝牙状态', res)
			if (res.available) {
				this.setData({
					available: true
				})
			} else {
				this.setData({
					available: false
				})
			}
		})
	},
	dialogClost() {
    this.setData({
      beforeClose: (action) =>
        new Promise((resolve) => {
          if (action === 'confirm') {
            // 确定按钮
            resolve(false)
          } else if (action === 'cancel') {
            // 取消按钮
            resolve(true)
          }
        }),
    })
  },
  init() {
    blueTool.initBlueTooth()
  },
  goBindEq() {
    this.setData({
			devices: []
		})
		if(this.data.available) {
			this.setData({
				showDialog: true
			})
			this.onConfirm()
		} else {
			wx.showToast({
				title: '蓝牙初始化失败,请打开蓝牙',
				icon: 'none',
				duration: 2000
			})
		}
  },
  onCancel() {
		this.dialogClost()
    clearInterval(this.timeValue)
    this.setData({
      showDialog: false
    })
  },
  createDiaTitle() {
		let num = 15
		let value = ''
		this.timeValue = setInterval(() => {
			value = `蓝牙搜索中(${num}s)...`
			if (num === 0) {
				clearInterval(this.timeValue)
				value = `蓝牙搜索完成`
			} else {
				num --
			}
			this.setData({
				bindDeviceTextInfo: value
			})
		}, 1000)
	},
  onConfirm() {
    console.log('onConfirm重新搜索');
    this.dialogClost()
		clearInterval(this.timeValue)
    this.createDiaTitle()
		blueTool.stopSearchBlueTooth()
    this.start()
  },
  start() {
    blueTool
      .startSearchBlueTooth().then(() => {
        wx.onBluetoothDeviceFound(({ devices }) => {
          console.log(devices, '发现的设备')
          this.setDevices(devices)
        })
      })
  },
  copy() {
    wx.setClipboardData({//复制文本
      data: JSON.stringify(this.waveChartOptions),
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: "none",
          mask: "true"//是否设置点击蒙版，防止点击穿透
        })
      }
    })
  },

  setDevices(devices) {
    // console.log('devices', devices.length)
    devices.forEach((device) => {
      if (!device.name && !device.localName) {
        return
      }
      if (!(device.name || device.localName).includes('Checkme')) {
        return
      }
      const foundDevices = this.data.devices
      const idx = inArray(foundDevices, 'deviceId', device.deviceId)
      const data = {}
      if (idx === -1) {
        data[`devices[${foundDevices.length}]`] = device
      } else {
        data[`devices[${idx}]`] = device
      }
			console.log(data)
      wx.hideLoading()
      this.setData(data)
			console.log(this.data.devices, 'devices')

    })
  },

  onConnect(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    blueTool.offOnChange()
    const name = ds.name
    blueTool.stopSearchBlueTooth().then(() => {
      blueTool.createDevice({
        deviceId
      }).then((res) => {
        setTimeout(() => {
          this.setData({
            showDialog: false,
            connected: true,
            deviceId
          })
          this.onSelectA(name, deviceId)
          blueTool.getMacDir(res, bytesArray => {
            this.bytesArray = this.bytesArray.concat(bytesArray)
            this.parseFile(this.bytesArray)
          })
        }, 1000)
      }).catch(() => {
        this.onSelectA(e)
      })
    })
  },
  onSelectA(e) {
    const value = e.currentTarget.dataset.item
		this.setData({
			saveDevice: value
		})
    const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
    let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name:this.data.saveDevice.name,deviceId: this.data.saveDevice.deviceId}
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.putData(saveDataList, '保存')
      this.goBackDoTest(this.data.saveDevice)
		}
  },
  handlerDetail(e) {
    const value = e.currentTarget.dataset.item
    this.goBackDoTest(value)
  },
  goBackDoTest(device) {
    let pages = getCurrentPages();  //获取当前页面
    let beforePage = pages[pages.length - 2]  //获取上一个页面的实例
    if (beforePage.bindEquipment) {
      beforePage.bindEquipment(device)
    }
    wx.navigateBack({
      delta: 1
    })
  },

  parseFile(bytesArray) {
    for (let i = 0; i < bytesArray.length - 7; i++) {
      if (bytesArray[i] !== '55' || bytesArray[i + 1] != "00" || bytesArray[i + 2].toLocaleLowerCase() !== 'ff') {
        continue
      }

      const len = hexStr2Num(dataConversion(bytesArray.slice(5, 7).join('')))
      if (i + 8 + len > bytesArray.length) {
        continue
      }

      const temp = bytesArray.slice(i, i + 8 + len)

      if (temp[temp.length - 1] === crc8(temp)) {
        // console.log('temp', temp)
        const res = parseResponse(temp)
        if (this.state === 0) {
          this.state = 1
          this.bytesArray = []
          this.fileData = []
          const buffSize = hexStr2Num(res.contentStr)
          console.log(buffSize, 'bufferSize')
          this.packageNumMax = Math.floor(buffSize / 512)
          this.readContent()
        } else if (this.state === 1) {
          this.fileData = this.fileData.concat(res.content)
          if (this.packageNumMax <= this.packageNum) {
            this.parseFileByFileType()
            this.stopReadPkg()
          } else {
            this.packageNum++
            this.readContent()
          }
        }
      }
    }
  },

  startReadPkg() {
    this.state = 0
    this.contentData = []
    this.packageNum = 0
    this.bytesArray = []

    startReadPkg({
      deviceId: this.data.deviceId,
      fileName: this.fileName
    })
  },

  readContent() {
    readFileData({
      deviceId: this.data.deviceId,
      packageNum: this.packageNum
    })
  },

  stopReadPkg() {
    this.state = 2
    stopReadPkg({
      deviceId: this.data.deviceId
    })
  },

  parseFileByFileType() {
    switch (this.fileType) {
      case 'ecg-list':
        this.parseEcgList()
        break;

      case 'ecg-item':
        this.parseEcgItem()
        break

      case 'oxi-list':
        this.parseOxiList()
        break

      case 'tmp-list':
        this.parseTmpList()
        break

      default:
        break;
    }
  },

  async readEcg(e) {
    this.fileName = 'ecg.dat'
    this.fileType = 'ecg-list'
    this.ecgData = []
    this.startReadPkg()
  },

  async readEcgFileItem(e) {
    this.fileType = 'ecg-item'
    const ds = e.currentTarget.dataset
    const fileName = ds.fileName
    this.fileName = fileName

    // console.log('readEcgFileItem', fileName)
    this.startReadPkg()
  },

  readTmp(e) {
    this.fileName = 'tmp.dat'
    this.fileType = 'tmp-list'
    this.startReadPkg()
  },

  readOxi(e) {
    this.fileType = 'oxi-list'
    this.fileName = 'oxi.dat'
    this.startReadPkg()
  },

  close(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId

    this.setData({
      deviceId
    }, () => {
      blueTool.closeDevice(deviceId)
        .then(() => {
          this.setData({
            connected: false,
            ecgData: [],
            devices: [],
            result: null
          })
        })
    })
  },

  parseEcgList() {
    const data = formatEcgData(this.fileData)
    if (data) {
      this.setData({
        ecgFiles: data
      })
    }
  },

  parseEcgItem() {
    const ecgItemData = parseEcgFileData(this.fileData)
    if (ecgItemData.waveList) {
      const options = getEcgWaveChart(ecgItemData.waveList, this.fileName, 500)
      //   ecgItemData.waveChartOptions = options
      delete ecgItemData.waveList
      this.data.showWaveEchart = true
      this.waveChartOptions = options
    }
    // console.log(ecgItemData, 'ecgItemData')
    this.setData({
      label: `ecg-${this.fileName}数据`,
      result: JSON.stringify(ecgItemData, null, 4)
    })
  },

  parseOxiList() {
    const data = formatOxiData(this.fileData)
    if (data) {
      this.setData({
        label: '脉指数据',
        result: JSON.stringify(data, null, 4)
      })
    }
  },

  parseTmpList() {
    const data = formatTmpData(this.fileData)

    if (data) {
      this.setData({
        label: '体温数据',
        result: JSON.stringify(data, null, 4)
      })
    }
  },
  async get() {
    this.setData({
      bindDevice: []
    })
    try {
      this.setData({
        loading: true
      })
      const res = await api.post('/api/user/storage/get', {
        data: {
          'key': 'devicelist'
        }
      })
      if (res[0].value) {
        var array = JSON.parse(res[0].value)
        const listValue = array.filter(item => item.name === 'electro')
        if (listValue.length > 0) {
          this.setData({
            bindDevice: listValue[0].devicelist
          })
        }
      }
      this.setData({
        loading: false
      })
      console.log(this.data.bindDevice,'dddd')
    } catch (e) {
      console.log('get->', e)
      return null
    }
  },
  delEq(e) {
    const name = e.currentTarget.dataset.name
    const data = this.data.bindDevice.filter(item => {
      return item.name !== name
    })
    this.putData(data, '删除')
  },
  putData(deviceIdList, type) {
    let num = [{ name: 'electro', devicelist: deviceIdList }]
    num = JSON.stringify(num)
    this.doSavedevice(num, type)
  },
  // 储存设备
  async doSavedevice(result, type) {
    try {
      await api.post('/api/user/storage/set', {
        data: {
          'key': 'devicelist',
          'value': result
        }
      })
      wx.showToast({
        title: `${type}成功`,
        icon: 'none',
        duration: 3000
      })
      this.setData({ showDialog: false });
      this.get()
    } catch (e) {
      console.log('put->', e)
    }
  },
})